#include <xconfig.h>
#include <xsocketdefine.h>
#include <xsocket.h>
#include <iostream>
#if CONFIG_BCB
    #pragma hdrstop
#endif
#include "xtcpclient.h"
using namespace std;
namespace zdh
{
	XTCPClient::XTCPClient()
		:m_Active(false),
		 m_BlockFlag(true),
		 m_RemoteIP("127.0.0.1"),
		 m_RemotePort(1234)
	{
	}
	XTCPClient::~XTCPClient()
	{
		if( m_Active ) Disconnect();
	}
	void XTCPClient::Connect()
	{
		if( m_Active ) return;
		m_Active = true;
		m_Socket.Open(XST_SOCK_STREAM);
		XSocketAPI::SetBlockStatus(_HANDLE_(m_Socket),m_BlockFlag);
		struct sockaddr_in RemoteAddr;
		RemoteAddr.sin_family = AF_INET;
		RemoteAddr.sin_addr.s_addr = XSocketAPI::INet_addr(m_RemoteIP.c_str());
		RemoteAddr.sin_port = XSocketAPI::HostToNetworkShort(m_RemotePort);
		XSocketAPI::Connect(_HANDLE_(m_Socket),(const sockaddr *)&RemoteAddr,sizeof(sockaddr_in));
		OnConnect();
	}
	void XTCPClient::Disconnect()
	{
		if( !m_Active ) return;
		m_Active = false;
		OnDisconnect();
		m_Socket.Close();
	}
	void XTCPClient::setRemotePort(XWord aPort)
	{
		assert(!m_Active);
		m_RemotePort = aPort;
	}
	void XTCPClient::setRemoteIP(const XString & aRemoteIP)
	{
		assert(!m_Active);
		m_RemoteIP = aRemoteIP;
	}

	void XTCPClient::setBlockFlag(bool aBlockFlag)
	{
		assert(!m_Active);
		m_BlockFlag = aBlockFlag;
	}
}

